﻿using dz.db.util.core;
using dz.loger.core;
using dz.u9.jky.schema.Common;
using dz.util.core;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;

namespace dz.u9.webapi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public abstract class U9BaseController : Controller
    {
        protected string baseUrl,conStr;
        protected SqlUtils utils;
        public U9BaseController()
        {
            baseUrl = Config.Instance.GetValue("u9url");
            conStr = Config.Instance.GetConnectionString("U9");
            utils = new SqlUtils(conStr);
        }

        

        protected async Task<U9CResult> U9Invoke(string parm, ApiParm method)
        {
            DateTime dt1, dt2;

            dt1 = DateTime.Now;
            dt2 = DateTime.Now;
            string url = baseUrl + method.Url;
            string type = method.Desc;

            U9CResult result = new U9CResult();

            try
            {
                HttpUtil util = new HttpUtil();

                Dictionary<string, string> args = new Dictionary<string, string>();
                string token = U9CTokenUtil.Instance.GetToken();
                args.Add("token", token);

                WebResult webResult = await util.Post(url, parm, args);

                result = JsonUtil.Deserialize<U9CResult>(webResult.Data);

            }
            catch (Exception ex)
            {
                LogUtil.Instance.Debug(ex);
                result.IsSuccess = false;
                result.Message = ex.Message;
                result.Data = ex.StackTrace;
            }
            finally
            {
                dt2 = DateTime.Now;

                int flag = result.IsSuccess ? 1 : -1;

                string sql = $@"insert into dz_api_invoke(url,data,flag,xtype,rtn,dstart,dend)
                values('
                {url}','{JsonUtil.Serialize(parm)}',{flag},'{type}','{JsonUtil.Serialize(result)}','{dt1}','{dt2}')";

                await utils.ExecuteNonQuery(sql);

            }
            return result;
        }
    }

    public struct ApiParm
    {
        public string Url;
        public string Desc;
    }
}
